<?php
function getSiteId($domain)
{
	require_once '\\\\192.168.100.20\var\tutf.dede.com\data\utf_base\enums\sites.php';
	foreach($em_sitess as $key=>$val)
	{
		if ($domain == $val)
		{
			return $key;
		}
	}
	return false;
}

function daddslashes($string, $force = 0, $strip = FALSE) {
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = daddslashes($val, $force, $strip);
			}
		} else {
			$string = addslashes($strip ? stripslashes($string) : $string);
		}
	}
	return $string;
}

function isPost()
{
	return 'POST' == $_SERVER["REQUEST_METHOD"] ? true : false;
}

function deldir($dir) {
	$dh=opendir($dir);
	while ($file=readdir($dh)) {
		if($file!="." && $file!="..") {
			$fullpath=$dir."/".$file;
			if(!is_dir($fullpath)) {
				unlink($fullpath);
			} else {
				deldir($fullpath);
			}
		}
	}
	closedir($dh);
		  
	if(rmdir($dir)) {
		return true;
	} else {
		return false;
	}
}

function array_get_unique($array,$key)
{
	$get	= array();
	foreach ($array as $val)
	{
		if (isset($val[$key])) $get[] = $val[$key];
	}
	return $get;
}

function array_get($array,$key){
	$get = array();
	foreach($array as $k => $val){
		if(in_array($k,$key)) {
			$get[$k] = $val;
		}
	}
	return $get;
}

function sort_combine($array,$key,$unique=false){
	$combine = array();
	foreach($array as $val){
		if($unique) $combine[$val[$key]] = $val;
		else $combine[$val[$key]][] = $val;
	}
	return $combine;
}
/**
 * 把数组按键排序
 *
 * @param array $array
 * @return array
 */
function sort_array($array,$field ){
	$sort = array();
	$active = array();
	
	foreach($array as $key=>$val){
		$sort[$key] = $val[$field];
	}
	natsort($sort);
	
	$i = 1;
	foreach($sort as $key=>$val){
		$sorts[$i] = $array[$key];
		$i++;
	}
	
	$count = count($sorts);
	for($i=$count;$i>=1;$i--){
		$active[] = $sorts[$i];
	}
	return $active;
}

function randStr($len=6,$format='ALL') { 
	switch($format) { 
		case 'ALL':
			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; break;
		case 'CHAR':
			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~'; break;
		case 'NUMBER':
			$chars='0123456789'; break;
		default :
			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; 
		break;
	}
	mt_srand((double)microtime()*1000000*getmypid()); 
	$password="";
	while(strlen($password)<$len)
		$password.=substr($chars,(mt_rand()%strlen($chars)),1);
	return $password;
} 

/**
 * 翻页函数
 *
 * @param int $num 总纪录数
 * @param int $perpage 每页大小
 * @param int $curpage 当前页面
 * @param string $mpurl url
 * @return string 类似于: <div class="page">***</div>
 */
function page($num, $perpage, $curpage, $mpurl) {
	$multipage = '';
	$mpurl .= strpos($mpurl, '?') ? '&' : '?';
	if($num > $perpage) {
		$page = 10;
		$offset = 2;

		$pages = @ceil($num / $perpage);

		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $from + $page - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if($to - $from < $page) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $pages - $page + 1;
				$to = $pages;
			}
		}

		#<span class="selected">1</span><a href="f1803-2">2</a><a href="f1803-3">3</a><span>...</span><a href="f1803-93">93</a><a title="下一页" class="next" href="f1803-2"><span>下一页</span></a>

		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'page=1" class="first"'.$ajaxtarget.'>1 ...</a>' : '').
			($curpage > 1 && !$simple ? '<a href="'.$mpurl.'page='.($curpage - 1).'" class="previous"'.$ajaxtarget.'><span>上一页</span></a>' : '');
		for($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<span class="selected">'.$i.'</span>' :
				'<a href="'.$mpurl.'page='.$i.($ajaxtarget && $i == $pages && $autogoto ? '#' : '').'"'.$ajaxtarget.'>'.$i.'</a>';
		}

		$multipage .= ($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="next"'.$ajaxtarget.'><span>下一页</span></a>' : '').
			($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="last"'.$ajaxtarget.'>... '.$realpages.'</a>' : '').
			(!$simple && $pages > $page && !$ajaxtarget ? '<kbd><input type="text" name="custompage" size="3" onkeydown="if(event.keyCode==13) {window.location=\''.$mpurl.'-\'+this.value; return false;}" /></kbd>' : '');

		#$multipage = $multipage ? '<div class="page"><span class="right">'.$multipage.'</span>共 <span class="blue">'.$num.'</span> 条信息 </div>' : '';
	}
	return $multipage;
}

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

//无阻塞模式请求URL
//function sfopensocket($url,$method)
//{
//	$fp = fsockopen('17.gangtai.org',80,$errno,$errstr,10);
//	stream_set_blocking($fp,true);
//	stream_set_timeout($fp,30);
//	if (!$fp)
//	{
//	    die("$errstr($errno)<br/>\n");
//	}
//	else
//	{
//		///keyword/getkeyword/cookie/{$params['setcookie']}/sd/{$params['sd']}/ed/{$params['ed']}/id/{$params['id']}/p/$i
//	    $out = "GET  HTTP/1.1\r\n";
//	    $out .= "Host: 17.gangtai.org\r\n";
//	    $out .= "Accept: */*\r\n";
//	    $out .= "Accept-Language: zh-cn\r\n";
//	    $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
//	    $out .= "Accept-Encodeing: gzip, deflate\r\n";
//	    $out .= "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.40607)\r\n";
//	    $out .= "Content-Length: 0\r\n";
//	    $out .= "Cache-Control: no-cache\r\n";
//	    $out .= "Connection: close\r\n";
//	    $out .= "Cookie: \r\n\r\n";
//	    $out .= "\r\n\r\n";
//	    fputs($fp,$out);
//	}
//	echo 'done';
//}

function sfopensocket($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 5, $block = TRUE) {
		$return = '';
		$matches = parse_url($url);
		!isset($matches['host']) && $matches['host'] = '';
		!isset($matches['path']) && $matches['path'] = '';
		!isset($matches['query']) && $matches['query'] = '';
		!isset($matches['port']) && $matches['port'] = '';
		$host = $matches['host'];
		$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
		$port = !empty($matches['port']) ? $matches['port'] : 80;
		
		if ($cookie)
		{
			foreach ($cookie as $key=>$val)
			{
				$Cookie[] = $key.'='.$val;
			}
			$cookie = join('; ',$Cookie);
		}
		
		if($post) {
			$out = "POST $path HTTP/1.0\r\n";
			$out .= "Accept: */*\r\n";
			//$out .= "Referer: $boardurl\r\n";
			$out .= "Accept-Language: zh-cn\r\n";
			$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
			//$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
			$out .= "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/15.0.845.0 Safari/535.1\r\n";
			$out .= "Host: $host\r\n";
			$out .= 'Content-Length: '.strlen($post)."\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Cache-Control: no-cache\r\n";
			$out .= "Connection: keep-alive";
			$out .= "Cookie: $cookie\r\n\r\n";
			$out .= $post;
		} else {
			$out = "GET $path HTTP/1.0\r\n";
			$out .= "Accept: */*\r\n";
			$out .= "Connection: keep-alive";
			//$out .= "Referer: $boardurl\r\n";
			$out .= "Accept-Language: zh-cn\r\n";
			//$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
			$out .= "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/15.0.845.0 Safari/535.1\r\n";
			$out .= "Host: $host\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Cookie: $cookie\r\n\r\n";
		}
		$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
		if(!$fp) {
			return '';
		} else {
			stream_set_blocking($fp, $block);
			stream_set_timeout($fp, $timeout);
			@fwrite($fp, $out);
			if ($block)
			{
				$status = stream_get_meta_data($fp);
				if(!$status['timed_out']) {
					while (!feof($fp)) {
						if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
							break;
						}
					}
	
					$stop = false;
					while(!feof($fp) && !$stop) {
						$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
						$return .= $data;
						if($limit) {
							$limit -= strlen($data);
							$stop = $limit <= 0;
						}
					}
				}
			}
			@fclose($fp);
			return $return;
		}
	}

function get_real_ip()
{
    $ip=false;
    if(!empty($_SERVER["HTTP_CLIENT_IP"]))
    {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) 
    {
        $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
        if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
        for ($i = 0; $i < count($ips); $i++) 
        {
            if (!eregi ("^(10│172.16│192.168).", $ips[$i])) 
            {
                $ip = $ips[$i];
                break;
            }
        }
     }
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}

function mdir($dir)
{
   	$dir = str_replace('\\','/',$dir);
   	$dir = explode('/',$dir);
   	$d = '';
   	foreach ($dir as $val)
   	{
   		$d .= $val.'/';
   		is_dir($d) || @mkdir($d);
   	}
}

function _sizecount($filesize) {
	if($filesize >= 1073741824) {
		$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
	} elseif($filesize >= 1048576) {
		$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
	} elseif($filesize >= 1024) {
		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
	} else {
		$filesize = $filesize . ' Bytes';
	}
	return $filesize;
}

function _getcookie($cookie)
{
	$return = array();
	$cookie	= explode('&',$cookie);
	foreach ($cookie as $value)
	{
		list($key,$val)	= explode('=',$value);
		$return[$key]	= $val;
	}
	return $return;
}

function ob_gzip($content) // $content 就是要压缩的页面内容，或者说饼干原料
{ 
	if( !headers_sent() && // 如果页面头部信息还没有输出
		extension_loaded("zlib") && // 而且zlib扩展已经加载到PHP中
		strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip")) //而且浏览器说它可以接受GZIP的页面 
	{
		$content = gzencode($content,9);// 为准备压缩的内容贴上“//此页已压缩”的注释标签，然后用zlib提供的gzencode()函数执行级别为9的压缩，这个参数值范围是0-9，0表示无压缩，9表示最大压缩，当然压缩程度越高越费CPU。

		//然后用header()函数给浏览器发送一些头部信息，告诉浏览器这个页面已经用GZIP压缩过了！ 
		header("Content-Encoding: gzip"); 
		header("Vary: Accept-Encoding");
		header("Content-Length: ".strlen($content));
	}
	return $content; //返回压缩的内容，或者说把压缩好的饼干送回工作台。
}


function dict($text)
{
	$text	= preg_replace("/[\s]{2,}/","",$text); 
	$dict	= scws_new();
	$dict->set_charset('utf-8');
	$dict->set_dict('/usr/local/scws/etc/dict.utf8.xdb');
	$dict->set_rule('/usr/local/scws/etc/rules.ini');
	$dict->set_ignore(true);
	$dict->set_multi(false);
	$dict->set_duality(false);
	
	$dict->send_text($text);
	$array	= $dict->get_tops();
	/*foreach ($array as $key=>$val)
	{
		if (strstr($val['attr'],'r') 
			|| strstr($val['attr'],'v')
			|| strstr($val['attr'],'g')
			|| strstr($val['attr'],'u')
			|| strstr($val['attr'],'a')
			|| strstr($val['attr'],'p')
		) 
			
		unset($array[$key]);
	}*/
	return $array;
}